package com.heima.juc.n8;

import com.heima.juc.n2.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author : leimingchao
 * @date Date : 2022年02月20日 19:09
 */
@Slf4j(topic = "c.TestCountDownLatch")
public class TestCountDownLatch {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(4);
        CountDownLatch countDownLatch = new CountDownLatch(3);
        pool.submit(() -> {
            log.debug("begin...");
            Sleeper.sleep(1);
            countDownLatch.countDown();
            log.debug("end...{}",countDownLatch.getCount());
        });

        pool.submit(() -> {
            log.debug("begin...");
            Sleeper.sleep(2);
            countDownLatch.countDown();
            log.debug("end...{}",countDownLatch.getCount());
        });

        pool.submit(() -> {
            log.debug("begin...");
            Sleeper.sleep(1.5);
            countDownLatch.countDown();
            log.debug("end...{}",countDownLatch.getCount());
        });

        pool.submit(() -> {
            try {
                log.debug("waiting....");
                countDownLatch.await();
                log.debug("end...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    private static void test() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        new Thread(() -> {
            log.debug("begin...");
            Sleeper.sleep(1);
            countDownLatch.countDown();
            log.debug("end...");
        }, "t1").start();

        new Thread(() -> {
            log.debug("begin...");
            Sleeper.sleep(2);
            countDownLatch.countDown();
            log.debug("end...");
        }, "t2").start();

        new Thread(() -> {
            log.debug("begin...");
            Sleeper.sleep(1.5);
            countDownLatch.countDown();
            log.debug("end...");
        }, "t3").start();
        log.debug("waiting....");
        countDownLatch.await();
        log.debug("wait end ...");
    }
}
